#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "core/hpcr_tcp.h"
#include "hpcr_log.h"

hpcr_fd_t hpcr_http_fd(char *addr, hpcr_uint16_t port)
{
    // 创建socket
    hpcr_fd_t fd = socket(AF_INET, SOCK_STREAM, 0);
    assert(fd >= 0);

    // 绑定地址
    hpcr_uint32_t addr_u = inet_addr(addr);
    struct sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_port = htons(port);
    address.sin_addr.s_addr = addr_u;
    int ret = bind(fd, &address, sizeof(address));
    assert(ret == 0);

    // 地址复用
    int on = 1;
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    // 开启监听
    ret = listen(fd, BACKLOG);
    assert(ret == 0);

    return fd;
}